import customTab from "../../../wxjs/customTab";
import uploadAliyun from "../../../UploadAliyun/uploadAliyun";
import QQMapWX from '../../../utils/qqmap-wx-jssdk.min.js'
var qqmapsdk;
const app = getApp();

function getFormData() {
  return {
    yPoint: '', //维度
    xPoint: '', //经度
    name: '', //定位当前名
    releaseContent: '', //输入内容
    releaseVideo: "{}", //视频
    releaseImg: "[]", //发布图片
    releaseCover: "{}", //发布封面
    releaseLabel: "", //标签
    releaseMention: "", //被@得人
    releaseStatus: "1", //发布状态。0草稿  1.已发布
    goodsUuid: "", //商品uuid
    remark: "",
  }
}

Page({
  data: {
    xhx_images: app.xhx_images,
    xhx_route: app.xhx_route,
    users: [], //@用户lists
    selCustomTags: [], //用户选中的自定义标签
    selPubTags: [], //用户选中的公共标签
    images: [], //用户选择图片资源
    videos: [
      // {
      //   path: '视频路径',
      //   width: 0, //视频宽
      //   height: 0, //视频长
      // }
    ], //用户选择视频资源
    form: getFormData(), //提交表单数据
  },
  onLoad: function(options) {
    const that = this;

    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'K36BZ-VOMHD-UYJ4Q-PC6NS-NFM3E-SBFXG'
    });

    // var myInfo = app.isNavigateToLogin();
    // if (!myInfo) return;

    // myInfo = app.isNavigateToBind();
    // if (!myInfo) return;
  },
  onShow: function() {
    const that = this;
    customTab(that, app, 1);
    if (!app.notifyCount) {
      wx.hideTabBarRedDot({
        index: 2,
      })
    }
  },
  getContent,
  inputFocus,
  inputBlur,
  navToNext,
  navToUsers,
  navToTag,
  close, //删除图片
  comfirm, //发布
  addMedia, //添加选择图片或视频
  chooseImage, //选择图片
  getImageInfo, //获取图片信息
  upLoadImgComplete, //图片上传回调
  chooseVideo, //选择视频
  upLoadVideoCover, //上传图片封面
  getLocation, //用户自选定位置
  delLocaltion, //用户取消选定位置
  getGoods, //用户分享商品
  push2Form, //操作数据写入到form，方便提交
})

function getContent(event) {
  const that = this;
  let releaseContent = event.detail.value;
  let users = that.data.users || [];
  let selCustomTags = that.data.selCustomTags || [];
  let selPubTags = that.data.selPubTags || [];
  let tags = selCustomTags.concat(selPubTags);
  let temp = {},
    tempUsers = [],
    tempTags = [];
  // 当前是否有@他人
  if (users.length > 0 && releaseContent.indexOf("@") != -1) {
    // @开头，空格结束的为@他人格式
    let regex = /\@(.+?)\ /g;
    // 每一个符合的结果
    let result;

    for (let i = 0; i < users.length; i++) {
      let isMatch = false;
      while ((result = regex.exec(releaseContent)) != null) {
        if (result[1] == users[i].username) {
          isMatch = true;
        }
      }

      if (isMatch) tempUsers.push(users[i]);
    }
    // 当前用户不匹配时才重新赋值
    if (users.length != tempUsers.length) temp.users = tempUsers;
  }

  // 当前是否有标签
  if (tags.length > 0 && releaseContent.indexOf("#") != -1) {
    // #开头，#结束的为标签格式
    let regex = /\#(.+?)\#/g;
    // 每一个符合的结果
    let result;

    for (let i = 0; i < tags.length; i++) {
      let isMatch = false;
      while ((result = regex.exec(releaseContent)) != null) {
        if (result[1] == tags[i].labelName) {
          isMatch = true;
        }
      }

      if (isMatch) tempTags.push(tags[i]);
    }
    console.log("tempTags", tempTags)
    console.log("tags", tags)

    // 当前用户不匹配时才重新赋值
    if (tags.length != tempTags.length) {
      temp.selPubTags = [];
      temp.selCustomTags = [];
      for (var i = 0; i < tempTags.length; i++) {
        if (tempTags[i].operateFlag == 1) {
          temp.selCustomTags.push(tempTags[i])
        } else if (tempTags[i].operateFlag == 2) {
          temp.selPubTags.push(tempTags[i])
        }
      }
    }
  }

  that.push2Form({
    releaseContent
  })
  that.setData(temp);
}

function inputFocus(event) {
  const that = this;
  let fixedBottom = event.detail.height || 0;
  // fixedBottom = fixedBottom - 48
  that.setData({
    fixedBottom,
  })
}

function inputBlur() {
  const that = this;
  let fixedBottom = 0;
  that.setData({
    fixedBottom,
  })
}

function navToNext(event) {
  const that = this;
  const url = event.currentTarget.dataset.url;

  var myInfo = app.isNavigateToLogin();
  if (!myInfo) return;

  myInfo = app.isNavigateToBind();
  if (!myInfo) return;

  if (url == "issueUsers") {
    that.navToUsers();
  } else if (url == "issueTag") {
    that.navToTag();
  }
}

function navToUsers() {
  const that = this;
  let users = that.data.users || [];

  if (users.length >= 3) return app.middleware.showToast("已达上限（3人）");

  wx.navigateTo({
    url: app.xhx_route["issueUsers"],
  })
}

function navToTag() {
  const that = this;
  var selCustomTags = that.data.selCustomTags || [];
  var selPubTags = that.data.selPubTags || [];
  var tags = selCustomTags.concat(selPubTags);

  if (tags.length >= 3) return app.middleware.showToast("已达上限（3个话题）");

  wx.navigateTo({
    url: app.xhx_route["issueTag"],
  })
}

function close(event) {
  const that = this;
  const index = event.currentTarget.dataset.index;
  var images = that.data.images || [];
  var videos = that.data.videos || [];

  if (videos.length > 0) {
    videos.splice(index, 1);
    that.setData({
      videos
    })
    return false;
  }

  if (images.length == 0) return;

  images.splice(index, 1);
  that.setData({
    images
  })
}

function comfirm(event) {
  const that = this;
  var form = that.data.form;
  var images = that.data.images;
  var videos = that.data.videos;
  var selCustomTags = that.data.selCustomTags;
  var selPubTags = that.data.selPubTags;
  var users = that.data.users;
  var selRelates = that.data.selRelates;
  var selGoods = that.data.selGoods;
  var tempImages = [];

  var myInfo = app.isNavigateToLogin();
  if (!myInfo) return;

  myInfo = app.isNavigateToBind();
  if (!myInfo) return;

  if (images.length > 0) {
    for (var i = 0; i < images.length; i++) {
      if (images[i].file) {
        tempImages.push(images[i]);
      }
    }
  }

  form.releaseContent = event.detail.value.releaseContent.trim();

  if (!form.releaseContent) return app.middleware.showToast("请输入内容");
  if (tempImages.length == 0 && videos.length == 0) return app.middleware.showToast("至少一张图片或视频");

  // console.log(form)
  // console.log(images)
  // console.log(videos)
  // console.log(selCustomTags)
  // console.log(selPubTags)
  // console.log(users)

  if (tempImages.length > 0) {
    form.releaseImg = JSON.stringify(tempImages);
    form.releaseCover = JSON.stringify(tempImages[0]);
  } else if (videos.length > 0) {
    form.releaseCover = JSON.stringify({
      file: videos[0].file + "?x-oss-process=video/snapshot,t_1,m_fast,w_800,f_png",
      width: videos[0].width, //视频宽
      height: videos[0].height, //视频长
    });
    // delete videos[0]["coverImg"];
    form.releaseVideo = JSON.stringify(videos[0]);
  }

  if (users) {
    users.forEach((item, index) => form.releaseMention += `${item.userId},`);
  }

  var tags = selCustomTags.concat(selPubTags);
  if (tags) {
    tags.forEach((item, index) => form.releaseLabel += `${item.uuid},`);
  }

  if (selRelates) {
    selRelates.forEach((item, index) => form.relationAccount = `${item.relationAccount}`);
  }

  if (selGoods) {
    selGoods.forEach((item, index) => form.goodsUuid = `${item.goodsUuid}`);
  }

  console.log(form)

  app.middleware.requestAjax({
    serAddr: app.serAddrs.contentAdd,
    data: form,
    success: function() {
      that.setData({
        form: getFormData(),
        images: [],
        videos: [],
        selCustomTags: [],
        selPubTags: [],
        users: [],
      }, function() {
        wx.switchTab({
          url: app.xhx_route.homeList,
        })
      })
    },
    complete: function(res) {
      app.middleware.showToast(res && res.msg || "发布失败");
    }
  })

}

function addMedia() {
  const that = this;
  var images = that.data.images || [];
  if (images.length > 0) {
    that.chooseImage();
    return false;
  }
  wx.showActionSheet({
    itemList: ["图片", "视频"],
    success: function(res) {
      const tapIndex = res.tapIndex;
      if (tapIndex == 0) { //图片
        that.chooseImage();
      } else if (tapIndex == 1) { //视频
        that.chooseVideo();
      }
    }
  })
}

function chooseImage() {
  const that = this;
  var images = that.data.images || [];
  wx.chooseImage({
    // count: 9 - images.length,
    count: 9,
    success: function(res) {
      const tempFilePaths = res.tempFilePaths;

      that.getImageInfo(tempFilePaths);
    }
  })
}

function getImageInfo(tempFilePaths, index) {
  const that = this;
  index = index || 0;
  wx.getImageInfo({
    src: tempFilePaths[index],
    success(res) {
      const width = res.width;
      const height = res.height;

      uploadAliyun(
        tempFilePaths[index],
        function(res) {
          console.log("上传成功", res)
          tempFilePaths[index] = {
            file: res,
            width,
            height,
          }
          that.upLoadImgComplete(tempFilePaths, index)
        },
        function(res) {
          console.log("上传失败")
          tempFilePaths[index] = {};
          that.upLoadImgComplete(tempFilePaths, index)
        }
      )
    }
  })
}

function upLoadImgComplete(tempFilePaths, index) {
  const that = this;
  var images = that.data.images || [];
  index++;
  if (index == tempFilePaths.length) {
    // images = images.concat(tempFilePaths);
    images = (tempFilePaths);
    that.setData({
      images,
    })
  } else {
    that.getImageInfo(tempFilePaths, index);
  }
}

function chooseVideo() {
  const that = this;

  wx.showModal({
    title: '提示',
    content: '拍摄视频请勿超过30s',
    showCancel: false,
    success: function() {
      wx.chooseVideo({
        // sourceType: ["camera"],
        maxDuration: 30,
        success: function(res) {
          console.log("chooseVideo", res)
          const duration = res.duration;
          const width = res.width;
          const height = res.height;
          const size = res.size;
          const tempFilePath = res.tempFilePath;
          const thumbTempFilePath = res.thumbTempFilePath;

          if (duration > 31) {
            wx.showModal({
              title: '提示',
              content: '视频时长超过30s',
              showCancel: false
            })
            return;
          }

          uploadAliyun(
            tempFilePath,
            function(res) {
              console.log("上传成功", res)
              that.setData({
                videos: [{
                  file: res,
                  width,
                  height,
                }],
              })
              // that.upLoadVideoCover(thumbTempFilePath);
            },
            function(res) {
              console.log("上传失败")
              wx.showToast({
                title: '上传失败',
                icon: "none"
              })
            }
          )
        }
      })
    }
  })
}


// 去除了
function upLoadVideoCover(thumbTempFilePath) {
  const that = this;
  var videos = that.data.videos || [];
  console.log("thumbTempFilePath", thumbTempFilePath)
  uploadAliyun(
    thumbTempFilePath,
    function(res) {
      console.log("上传成功", res)
      videos[0].coverImg = res;
      that.setData({
        videos,
      })
    },
    function(res) {
      console.log("上传失败")
      wx.showToast({
        title: '上传失败',
        icon: "none"
      })
    }
  )
}

function getLocation() {
  const that = this;

  wx.getSetting({
    success: function(res) {
      var userLocation = res.authSetting["scope.userLocation"];
      wx.chooseLocation({
        success: function(res) {
          console.log(res)
          const address = res.name;
          const yPoint = res.latitude;
          const xPoint = res.longitude;


          qqmapsdk.reverseGeocoder({
            location: {
              latitude: yPoint,
              longitude: xPoint
            },
            success: function(res) { //成功后的回调
              const address_component = res.result.address_component || {};
              const province = address_component.province;
              const city = address_component.city;
              const district = address_component.district;

              that.push2Form({
                province,
                city,
                district,
                address,
                yPoint,
                xPoint,
              })
            }
          });
        },
        fail: function(res) {
          console.log(res)
          if (((typeof userLocation) == "boolean") && res.errMsg == "chooseLocation:fail auth deny") {
            wx.showModal({
              title: '提示',
              content: '开启定位权限',
              success: function(res) {
                if (res.confirm) {
                  wx.openSetting({
                    success(res) {
                      console.log(res)
                      if (res.authSetting["scope.userLocation"]) {
                        that.getLocation();
                      }
                    },
                    fail: function(res) {
                      console.log(res)
                    }
                  })
                }
              }
            })
          }
        }
      })
    }
  })
}

function delLocaltion() {
  const that = this;
  that.push2Form({
    province: "",
    city: "",
    district: "",
    address: "",
    yPoint: "",
    xPoint: "",
  })
}

function getGoods() {
  const that = this;

}

function push2Form(data = {}) {
  const that = this;
  var form = that.data.form || {};
  Object.assign(form, data);
  that.setData({
    form: form
  })
}